package com.lkx.farmershop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.mapper.CommentsMapper;
import com.lkx.farmershop.model.dto.CommentsDto;
import com.lkx.farmershop.model.entity.Comments;
import com.lkx.farmershop.model.entity.Farmer;
import com.lkx.farmershop.model.vo.CommentsVo;
import com.lkx.farmershop.model.vo.SimpleUserVo;
import com.lkx.farmershop.service.CommentsService;
import com.lkx.farmershop.service.IFarmerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Comments)表服务实现类
 *
 * @author makejava
 * @since 2025-02-10 15:19:56
 */
@Service("commentsService")
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements CommentsService {

    @Autowired
    private IFarmerService farmerService;

    @Override
    public ApiResult<String> addComments(CommentsDto commentsDto) {
        // 保存评论信息
        Comments comments = new Comments(commentsDto.getTuanId(), commentsDto.getCommentsContent(),
                commentsDto.getParentId(), commentsDto.getUserId(), LocalDateTime.now(), commentsDto.getReplyUserId());
        save(comments);
        // 如果parentId为-1，则将parentId设置为此评论的id(设置父评论为自己)
        if (comments.getParentId()<0){
            comments.setParentId(comments.getId());
            updateById(comments);
        }

        return ApiResult.success("发表评论成功");

        /*//返回此评论给前端
        //给简化用户信息赋值
        SimpleUserVo simpleUserVo = new SimpleUserVo();
        Farmer user = farmerService.lambdaQuery()
                .eq(Farmer::getFarmerId, commentsDto.getUserId()).one();
        simpleUserVo.setUserId(user.getFarmerId());
        simpleUserVo.setUserName(user.getName());
        simpleUserVo.setAvatar(user.getAvatar());
        //创建返回值对象
        CommentsVo commentsVo = new CommentsVo();
        commentsVo.setSimpleUserVo(simpleUserVo);

        //给评论信息赋值
        commentsVo.setCommentsId(comments.getId());
        commentsVo.setCommentsContent(comments.getCommentsContent());
        commentsVo.setCommentsTime(comments.getCommentsTime());
        if (comments.getReplyUserId() != -1L){
            Farmer replyUser = farmerService.lambdaQuery()
                    .eq(Farmer::getFarmerId, comments.getReplyUserId()).one();
            commentsVo.setReplyUserName(replyUser.getName());
        }else{
            commentsVo.setReplyUserName("");
        }

        return ApiResult.success(commentsVo);*/
    }

    @Override
    public ApiResult<List<List<CommentsVo>>> getCommentsList(Long tuanId) {
        ////获取评论列表,判断此组团是否有评论
        List<Comments> commentsList = lambdaQuery().eq(Comments::getTuanId, tuanId).list();
        if(commentsList == null || commentsList.isEmpty()){
            return ApiResult.success(new ArrayList<>());
        }

        // 按照parentId分组
        Map<Long, List<Comments>> groupedComments = commentsList.stream()
                .collect(Collectors.groupingBy(Comments::getParentId));

        // 将分组结果添加到cListList
        List<List<Comments>> cListList = new ArrayList<>(groupedComments.values());

        //转化为返回值类型
        List<List<CommentsVo>> commentsVoListList = cListList.stream().map(cList ->
                    cList.stream().map(comments -> {
                    CommentsVo commentsVo = new CommentsVo();
                    //给评论信息赋值
                    commentsVo.setCommentsContent(comments.getCommentsContent());
                    commentsVo.setCommentsTime(comments.getCommentsTime());
                    commentsVo.setCommentsId(comments.getId());
                    commentsVo.setParentId(comments.getParentId());
                    //回复的用户的名字(replyUserId为-1即没有回复别人)
                    if (comments.getReplyUserId() < 0) {
                        commentsVo.setReplyUserName("");
                    }else{
                        commentsVo.setReplyUserName("回复 "+farmerService.lambdaQuery()
                                .eq(Farmer::getFarmerId, comments.getReplyUserId())
                                .one().getName()+"：");
                    }

                    //给简化用户信息赋值
                    Farmer user = farmerService.lambdaQuery()
                            .eq(Farmer::getFarmerId, comments.getUserId()).one();
                    SimpleUserVo simpleUserVo = new SimpleUserVo(user.getFarmerId(), user.getName(), user.getAvatar());
                    commentsVo.setSimpleUserVo(simpleUserVo);
                    return commentsVo;
                    }).collect(Collectors.toList()))
                .collect(Collectors.toList());

        //按时间排序
        for (List<CommentsVo> commentsVoList : commentsVoListList) {
            commentsVoList.sort(Comparator.comparing(CommentsVo::getCommentsTime));
        }
        commentsVoListList.sort(Comparator.comparing(o -> o.get(0).getCommentsTime()));
        return ApiResult.success(commentsVoListList);
    }
}

